﻿using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Threading;

namespace eHouse.ViewModels
{
    public class RuleViewModel : INotifyPropertyChanged
    {

        public bool IsDataLoaded
        {
            get;
            private set;
        }

        public ObservableCollection<ItemViewModel> Rules { get; private set; }

        public RuleViewModel()
        {
            this.Rules = new ObservableCollection<ItemViewModel>();
        }

        private AutoResetEvent wait;

        public bool Error = false;

        public void LoadRules(string sensor)
        {
            if (IsDataLoaded)
            {
                return;
            }

            using (wait = new AutoResetEvent(false))
            {
                App.ConnectionManager.LoadRules(sensor, OnRulesReceived);
                wait.WaitOne();
            }
        }

        private void OnRulesReceived(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
        {
            this.Rules = new ObservableCollection<ItemViewModel>();
            if (e.SocketError != System.Net.Sockets.SocketError.Success)
            {
                Error = true;
            }
            else
            {
                ICollection<Rule> rules = sender as ICollection<Rule>;
                foreach (Rule rule in rules)
                {
                    ItemViewModel item = new ItemViewModel();
                    item.LineOne = rule.Time;
                    item.LineTwo = rule.ToString();
                    item.SwitchState = rule.Id;
                    this.Rules.Add(item);
                }
            }
            wait.Set();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
